package com.javaee.ejb.session;

import java.util.List;
import com.javaee.ejb.entity.Project;
import com.javaee.ejb.session.remote.ProjectManagerRemote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class ProjectManager
 */
@Stateless
public class ProjectManager implements ProjectManagerRemote {

	@PersistenceContext
	private EntityManager entityManager;

	public ProjectManager() {
	}

	public int saveProject(Project project) {
		project = entityManager.merge(project);
		entityManager.persist(project);
		return project.getId();
	}

	@SuppressWarnings("unchecked")
	public List<Project> getListDashboardByEmployeeId(int employeeId) {
		Query query = entityManager
				.createQuery("SELECT DISTINCT project FROM Project project LEFT JOIN project.members members INNER JOIN FETCH project.manager manager WHERE members.id = :employeeId OR manager.id = :employeeId");
		query.setParameter("employeeId", employeeId);
		return (List<Project>) query.getResultList();
	}

	public Project getByIdWithMembers(int id) {
		Query query = entityManager
				.createQuery("FROM Project project LEFT JOIN FETCH project.members WHERE project.id = :id");
		query.setParameter("id", id);

		try {
			return (Project) query.getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}

	public Project getById(int id) {
		return entityManager.find(Project.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Project> getListAdministrationConsole() {
		Query query = entityManager
				.createQuery("SELECT project FROM Project project");
		return (List<Project>) query.getResultList();
	}

	public Project getByName(String projectName) {
		Query query = entityManager
				.createQuery("FROM Project project WHERE project.name = :projectName");
		query.setParameter("projectName", projectName);
		try {
			return (Project) query.getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}
}
